package com.baor.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baor.domain.LoginUser;
import com.baor.utils.RedisUtil;
import com.baor.security.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
@EnableWebSecurity
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        StringBuilder headers = new StringBuilder();
        Enumeration<String> headerNames = request.getHeaders("Access-Control-Request-Headers");
        if ( Objects.nonNull(headerNames) ){
            while( headerNames.hasMoreElements() )
                if (StringUtils.isBlank(headers.toString()))
                    headers.append(headerNames.nextElement());
                else
                    headers.append(",").append(headerNames.nextElement());
        }
        response.setHeader("Access-Control-Allow-Headers", headers.toString());
        response.setContentType("text/html;charset=utf-8");
        String uri = request.getRequestURI();
        Map<String,Object> res = new HashMap<>();
        // 白名单
        if ( uri.contains("login") ){
            filterChain.doFilter(request,response);
            return;
        }
        // 获取authorization
        String authorization = request.getHeader("authorization");//authorization
        if ( authorization == null || authorization.equals("") )
        {
            authorization =request.getParameter("authorization");
        }
        // 验证authorization
        if ( authorization == null || authorization.equals("") ){
            res.put("code", "403");
            res.put("msg", "用户信息不存在");
            response.getWriter().print(res);
            return;
        }
        // 解析authorization
        Claims claims = tokenService.getBody(authorization);
        if ( claims == null ){
            res.put("msg","token不存在或已过期");
            response.getWriter().print(res);
            return;
        }

        String userAccount = claims.getSubject();
        LoginUser loginUser = (LoginUser) redisUtil.getValue("userAccount:"+userAccount);
        String status = redisUtil.getValue("loginUser:"+loginUser).toString();
        if ( !status.equals(authorization) ){
            response.getWriter().print("请重新登录");
            return;
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = null;
        try{
            usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }catch (Exception e){
            System.out.println("error");
            response.getWriter().append("token不存在");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
